package net.hvacapp.cmvrfforandroid.ui.fragment;


import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.support.v4.app.Fragment;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;

import net.hvacapp.cmvrfforandroid.R;
import net.hvacapp.cmvrfforandroid.adapter.BaseAdapterHelper;
import net.hvacapp.cmvrfforandroid.adapter.QuickAdapter;
import net.hvacapp.cmvrfforandroid.constant.Constant;
import net.hvacapp.cmvrfforandroid.http.BasicHttpClient;
import net.hvacapp.cmvrfforandroid.http.HttpCallbackHandle;
import net.hvacapp.cmvrfforandroid.http.HttpConstant;
import net.hvacapp.cmvrfforandroid.manager.AccountManager;
import net.hvacapp.cmvrfforandroid.manager.ProjectManager;
import net.hvacapp.cmvrfforandroid.model.project.Project;
import net.hvacapp.cmvrfforandroid.ui.EventBus.ProjectListRefreshEvent;
import net.hvacapp.cmvrfforandroid.ui.listener.OnStateChangeListener;
import net.hvacapp.cmvrfforandroid.ui.project.BrowserActivity;
import net.hvacapp.cmvrfforandroid.ui.project.ProjectStatusModifyActivity;
import net.hvacapp.cmvrfforandroid.ui.project.model.GetProjectInfoDataResp;
import net.hvacapp.cmvrfforandroid.ui.project.model.ProjectInfoData;
import net.hvacapp.cmvrfforandroid.utils.AnnotationUtil;
import net.hvacapp.cmvrfforandroid.utils.DateTimeUtils;
import net.hvacapp.cmvrfforandroid.utils.NumberUtil;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.EFragment;
import org.androidannotations.annotations.FragmentArg;
import org.androidannotations.annotations.ViewById;

import java.util.HashMap;
import java.util.Map;

import de.greenrobot.event.EventBus;

/**
 * A simple {@link Fragment} subclass.
 */
@EFragment(R.layout.fragment_project_list)
public class ProjectListFragment extends BaseFragment implements OnStateChangeListener{

    @ViewById
    PullToRefreshListView lv_project;
    @FragmentArg
    int typeValue;

    private int begin;
    private int end;
    
    private QuickAdapter<ProjectInfoData> mQuickAdapter;
    
    public ProjectListFragment() {
        // Required empty public constructor
    }


    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            
        }
    }
    
    @Override
    public void onStateChange() {
        if (this.isAdded()){

        }
    }
    
    @AfterViews
    public void init(){
        initView();
        EventBus.getDefault().register(this);
        
        if (mQuickAdapter == null){
            mQuickAdapter = new QuickAdapter<ProjectInfoData>(getActivity(),R.layout.text_detail_item) {
                @Override
                protected void convert(BaseAdapterHelper helper, ProjectInfoData item) {
                    String desc = NumberUtil.formateDouble(item.getArea()) + "平米 " + item.getOwnerName() + " " + item.getOwnerContact();
                    helper.setText(R.id.tv_title,item.getHouse())
                            .setText(R.id.tv_description,desc)
                            .setText(R.id.tv_date, DateTimeUtils.getDate(item.getTime()));
                    if (typeValue == ProjectInfoData.PROJECT_PHASE_DEAL + ProjectInfoData.PROJECT_PHASE_REVIEW) {
                        //显示状态
                        helper.setVisible(R.id.tv_status, true);
                        if (item.getPhase() == ProjectInfoData.PROJECT_PHASE_REVIEW) {
                            helper.setText(R.id.tv_status, "已审核");
//                            helper.setTextColorRes(R.id.tv_status, R.color.cm_blue_color);
                        }
                        else {
                            helper.setText(R.id.tv_status, "待审核");
//                            helper.setTextColorRes(R.id.tv_status, R.color.cm_blue_color);
                        }
                    }
                    else if (typeValue == ProjectInfoData.PROJECT_SUB) {
                        helper.setVisible(R.id.tv_status, true);
                        helper.setText(R.id.tv_status, item.getUserContactName());
                    }
                    else if (typeValue == ProjectInfoData.PROJECT_PHASE_ALL) {
                        helper.setVisible(R.id.tv_status, true);
                        if (item.getPhase() == ProjectInfoData.PROJECT_PHASE_INPROGRESS) {
                            helper.setText(R.id.tv_status, "进行中");
                        }
                        else if (item.getPhase() == ProjectInfoData.PROJECT_PHASE_NOTDEAL) {
                            helper.setText(R.id.tv_status, "未成交");
                        }
                        else if (item.getPhase() == ProjectInfoData.PROJECT_PHASE_REVIEW) {
                            helper.setText(R.id.tv_status, "已成交，已审核");
                        }
                        else {
                            helper.setText(R.id.tv_status, "已成交，待审核");
                        }
                    }
                    else {
                        helper.setVisible(R.id.tv_status, false);
                    }
                }
            };
        }
        
        lv_project.getRefreshableView().setAdapter(mQuickAdapter);
        
        initData();
        
        initListener();
    }

    /**
     * 初始化下拉刷新控件
     */
    public void initView() {
        // 收费用户版本
        Drawable loadingDrawable = getResources().getDrawable(
                R.drawable.ptr_down_arrow);
        lv_project.getLoadingLayoutProxy().setPullLabel(
                getString(R.string.pull_label));

        lv_project.getLoadingLayoutProxy().setPullLabel(
                getString(R.string.pull_label));
        lv_project.getLoadingLayoutProxy().setRefreshingLabel(
                getString(R.string.pull_refreshing_label));
        lv_project.getLoadingLayoutProxy().setReleaseLabel(
                getString(R.string.pull_release_label));

        lv_project.getLoadingLayoutProxy().setLoadingDrawable(
                loadingDrawable);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
    }

    /**
     * 联系人任务未处理
     *
     * @param event
     */
    public void onEvent(ProjectListRefreshEvent event) {
        loadProjectInfo(typeValue, 0, -1);
    }

    private void initListener() {
        lv_project.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                ProjectInfoData data = (ProjectInfoData)parent.getItemAtPosition(position);
                ProjectManager.getInstance().setProjectData(data);
                if (data.getPhase() == 1) {
                    startActivity(new Intent(getActivity(), AnnotationUtil.get(ProjectStatusModifyActivity.class)));
                }
                else {
                    //查看项目报告
                    startActivity(new Intent(getActivity(), AnnotationUtil.get(BrowserActivity.class)));
                }
            }
        });

        lv_project.setOnRefreshListener(
                new PullToRefreshBase.OnRefreshListener<ListView>() {
                    @Override
                    public void onRefresh(PullToRefreshBase<ListView> refreshView) {
                        // loadAccountDynamicData();
                        // 下拉刷新
                        if (refreshView.getCurrentMode().equals(PullToRefreshBase.Mode.PULL_FROM_START)) {
                            // 下拉刷新
                            initData();
                        } else {
                            // 上拉加载更多
                            loadMoreData();
                        }
                    }
                }

        );
    }

    private void initData() {
        begin = 0;
        end = Constant.PAGE_COUNT + begin - 1;
        if (typeValue != ProjectInfoData.PROJECT_SUB) {
            loadProjectInfo(typeValue, begin, end);
        }
        else {
            loadSubProjectInfo(begin, end);
        }
    }

    private void loadMoreData() {
        begin = mQuickAdapter.getCount();
        end = Constant.PAGE_COUNT + begin - 1;
        if (typeValue != ProjectInfoData.PROJECT_SUB) {
            loadProjectInfo(typeValue, begin, end);
        }
        else {
            loadSubProjectInfo(begin, end);
        }
    }

    private void loadProjectInfo(int phase, final int begin, int end) {
        Map<String, Object> param = new HashMap<>();

        param.put("si", begin);
        param.put("ei", end);
        param.put("p", phase);


        BasicHttpClient.httpGetAsync(HttpConstant.HTTP_GET_ALL_PROJECTS, AccountManager.getInstance().getToken(), param, new HttpCallbackHandle<GetProjectInfoDataResp>() {
            @Override
            public void onSuccess(GetProjectInfoDataResp obj) {
                // 成功
                if (begin == 0) {
                    //刷新
                    mQuickAdapter.clear();
                }
                else {

                }
                mQuickAdapter.addAll(obj.getGetProjectsResult());
                lv_project.onRefreshComplete();
            }

            @Override
            public void onFailure(String response) {
                lv_project.onRefreshComplete();

            }

        });
    }

    private void loadSubProjectInfo(final int begin, int end) {
        Map<String, Object> param = new HashMap<>();

        param.put("si", begin);
        param.put("ei", end);


        BasicHttpClient.httpGetAsync(HttpConstant.HTTP_GET_ALL_SUB_PROJECTS, AccountManager.getInstance().getToken(), param, new HttpCallbackHandle<GetProjectInfoDataResp>() {
            @Override
            public void onSuccess(GetProjectInfoDataResp obj) {
                // 成功
                if (begin == 0) {
                    //刷新
                    mQuickAdapter.clear();
                }
                else {

                }
                mQuickAdapter.addAll(obj.getGetChildUserProjectsResult());
                lv_project.onRefreshComplete();
            }

            @Override
            public void onFailure(String response) {
                lv_project.onRefreshComplete();
            }

        });
    }


}
